//
//  MCNetwork.swift
//  MCNetwork
//
//  Created by MC on 2018/7/13.
//  Copyright © 2018年 MC. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON





typealias Success<T> = (JSON) -> ()
typealias Failure<T> = (MCError<MCErrorDetail>) -> ()

struct MCErrorDetail {
    var code : String
    var message : String
}

enum MCError <T> {
    case codeError(T)
    case networkNull
    case wrongReturn
}

struct MCNetwork {
    

    
    @discardableResult
    public static func POST(_ url: String!, _ params:[String:Any]? = [String:Any](), vc:UIViewController? = nil,success: @escaping Success<JSON>, failure: Failure<MCError<MCErrorDetail>>? = nil) -> DataRequest {
        
        
        let hudSuperView = UIApplication.shared.keyWindow
        MCHUD_default(message: "加载中", view: hudSuperView, delay: 0)


        
        // 处理入参
        let nowParas = dealWithParas(params)

        let headers : HTTPHeaders = [
            "Content-Type":"application/json",
            "userToken"   : MCUserinfo_getToken()
        ]
        
        // 配置网络请求时间
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 10
        
        return manager.request(url, method: .post,
                                 parameters: nowParas,
                                 encoding: JSONEncoding.default,
                                 headers: headers)
            .responseJSON(queue: DispatchQueue.main) { (response) in
                
                MCHUD_hidden(view: hudSuperView)
                
                let result = response.result

                // 处理返回值
                dealWithResult(result: result, vc: vc, success: success, failure: failure)
        }
    }
}



/**
 * 对传入的参数的处理
 * 如果没传userId，storeId，pageSize， 就拼接上去拼接
 */
fileprivate func dealWithParas(_ para:Dictionary<String, Any>?) -> [String:Any] {
    
    var originDict = Dictionary<String, Any>.init()
    
    if para != nil {
        originDict = para!
    }
    let dictM = NSMutableDictionary.init(dictionary: originDict)
    
    let allkeys = originDict.keys
    if !allkeys.contains("userId") {
        dictM.setValue(MCUserinfo_getUserId(), forKey: "userId")
    }
    
    if !allkeys.contains("storeId") {
        dictM.setValue(MCUserinfo_getStoreId(), forKey: "storeId")
    }
    
    if !allkeys.contains("pageSize") {
        dictM.setValue("20", forKey: "pageSize")
    }
    
    return dictM as? [String : Any]  ?? [:]
}


/**
 * 处理返回结果
 */
fileprivate func dealWithResult(result:Result<Any>,vc:UIViewController? = nil,success: @escaping Success<JSON>, failure: Failure<MCError<MCErrorDetail>>? = nil) {
   
    // 网络异常 没访问到服务器
    if result.isFailure {
        if (failure != nil) {
            if (vc != nil) {
                UIAlertController.showAlert(message: "网络连接不畅，请检查网络设置", in: vc!)
            }
            failure!(.networkNull)
        }
    }
    
    
    if result.isSuccess {
        // 有效的返回的数据
        if let data = result.value as? [String:Any] {
            
            let code = data["code"] as? NSNumber ?? 0
            let message = data["message"] as? String ?? ""
            
            // 想要的返回的结果处理
            if code.intValue == MCCode_success {
                let json = JSON(data)
                success(json["data"])
            // token失效的处理
            } else if code.intValue == MCCode_token {
                MCAlterController_oneOptions(vc: vc, message: "该账号已在别处登录,请重新登录", cancle: {
                    let login = MCLoginPageViewController()
                    
                    var isHiddenBar = true
                    
                    let className = MCGetClassName(vc!)
                    if className == "MCHomePageViewController" || className == "MCActivityPageViewController" || className == "MCPersonalViewController" {
                        isHiddenBar = false
                    }
                    
                    
                    MCPushToViewController(current: vc!, target: login, isHiddenBottomBarWhenBack: isHiddenBar)
                })
            // 异常的结果处理
            } else {
                let error = MCErrorDetail(code: code.stringValue,message: message)
                MCAlterController_oneOptions(vc: vc, message: message,cancle: nil)
                if (failure != nil) {
                    failure!(.codeError(error))
                }
            }
        // 异常的数据结构
        } else {
            MCAlterController_oneOptions(vc: vc!, message: "异常的数据结构",cancle: nil)
            if (failure != nil) {
                failure!(.wrongReturn)
            }
        }
    }
}
